package com.zs.admin.service.wisdbook.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.zs.admin.AdminThreadLocal;
import com.zs.admin.service.wisdbook.IWisdbookUserService;
import com.zs.admin.validate.wisdbook.WisdbookUserCreateValidate;
import com.zs.admin.validate.wisdbook.WisdbookUserSearchValidate;
import com.zs.admin.validate.wisdbook.WisdbookUserUpdateValidate;
import com.zs.admin.validate.commons.IdValidate;
import com.zs.admin.validate.commons.PageValidate;
import com.zs.admin.vo.wisdbook.WisdbookUserDetailVo;
import com.zs.admin.vo.wisdbook.WisdbookUserListedVo;
import com.zs.admin.vo.system.SystemAuthAdminListedVo;
import com.zs.common.core.PageResult;
import com.zs.common.entity.wisdbook.WisdbookUser;
import com.zs.common.entity.system.SystemAuthAdmin;
import com.zs.common.mapper.WisdbookUserMapper;
import com.zs.common.mapper.system.SystemAuthAdminMapper;
import com.zs.common.util.StringUtils;
import com.zs.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 标记任务实现类
 * @author SwAdmin
 */
@Service
public class WisdbookUserServiceImpl implements IWisdbookUserService {
        
    @Resource
    WisdbookUserMapper wisdbookUserMapper;

    @Resource
    SystemAuthAdminMapper systemAuthAdminMapper;

    @Override
    public PageResult<SystemAuthAdminListedVo> selectUsers(PageValidate pageValidate, IdValidate idValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<SystemAuthAdmin> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.select("t.id,t.username,t.nickname,t.avatar," +
                        "t.role_ids as role,t.dept_ids as dept,t.is_multipoint," +
                        "t.is_disable,t.last_login_ip,t.last_login_time,t.create_time,t.update_time")
                .eq("t.is_delete", 0)
                .orderByDesc(Arrays.asList("t.id", "t.sort"));

        if (StringUtils.isNotNull(idValidate.getIds())) {
            mpjQueryWrapper.in("role_ids", idValidate.getIds().split(","));
        }

        IPage<SystemAuthAdminListedVo> iPage = systemAuthAdminMapper.selectJoinPage(
                new Page<>(page, limit),
                SystemAuthAdminListedVo.class,
                mpjQueryWrapper);
        return PageResult.iPageHandle(iPage);
    }

    @Override
    public WisdbookUserDetailVo get(WisdbookUserSearchValidate searchValidate) {

        QueryWrapper<WisdbookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);

        wisdbookUserMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "=:bookId@book_id:int"
        });
        WisdbookUserDetailVo vo=null;
        List<WisdbookUser> users = wisdbookUserMapper.selectList(queryWrapper);
        if (users!=null&&users.size()>0){
            vo = new WisdbookUserDetailVo();
            WisdbookUser  user = users.get(0);
            vo.setId(user.getId());
            vo.setBookId(user.getBookId());
            vo.setMarkUserId(user.getMarkUserId());
        }
        return vo;
    }

    /**
     * 标记任务列表
     *
     * @author SwAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<WisdbookUserListedVo>
     */
    @Override
    public PageResult<WisdbookUserListedVo> listByUser(PageValidate pageValidate, WisdbookUserSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        List<Integer> roles = AdminThreadLocal.getRoleIds();
        if(roles.size()>0 && roles.get(0)>1) searchValidate.setMarkUserId(AdminThreadLocal.getAdminId());

        MPJQueryWrapper<WisdbookUser> queryWrapper = new MPJQueryWrapper<WisdbookUser>()
                .selectAll(WisdbookUser.class)
                .select("book.name", "book.grade", "book.subject", "book.mark_status", "user.nickname","book.pid")
                .innerJoin("tb_wisdbook book on t.book_id = book.id")
                .leftJoin("tb_system_auth_admin user on t.mark_user_id = user.id")
                .eq("book.is_delete", 0)
                .orderByAsc("book.mark_status");
        if(searchValidate.getMarkUserId()!=null)
            queryWrapper.eq("t.mark_user_id", searchValidate.getMarkUserId());
        if(searchValidate.getBookId()!=null)
            queryWrapper.eq("t.book_id", searchValidate.getBookId());

        IPage<WisdbookUserListedVo> iPage = wisdbookUserMapper.selectJoinPage(new Page<>(page, limit), WisdbookUserListedVo.class, queryWrapper);

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    /**
     * 标记任务列表
     *
     * @author SwAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<WisdbookUserListedVo>
     */
    @Override
    public PageResult<WisdbookUserListedVo> list(PageValidate pageValidate, WisdbookUserSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<WisdbookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        wisdbookUserMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:id:int",
            "=:bookId@book_id:int",
            "=:markUserId@mark_user_id:int",
        });

        IPage<WisdbookUser> iPage = wisdbookUserMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<WisdbookUserListedVo> list = new LinkedList<>();
        for(WisdbookUser item : iPage.getRecords()) {
            WisdbookUserListedVo vo = new WisdbookUserListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 标记任务详情
     *
     * @author SwAdmin
     * @param id 主键参数
     * @return WisdbookUser
     */
    @Override
    public WisdbookUserDetailVo detail(Integer id) {
        WisdbookUser model = wisdbookUserMapper.selectOne(
                new QueryWrapper<WisdbookUser>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        WisdbookUserDetailVo vo = new WisdbookUserDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 标记任务新增
     *
     * @author SwAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(WisdbookUserCreateValidate createValidate) {
        WisdbookUser model = new WisdbookUser();
        model.setBookId(createValidate.getBookId());
        model.setMarkUserId(createValidate.getMarkUserId());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        wisdbookUserMapper.insert(model);
    }

    /**
     * 标记任务编辑
     *
     * @author SwAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(WisdbookUserUpdateValidate updateValidate) {
        WisdbookUser model = wisdbookUserMapper.selectOne(
                new QueryWrapper<WisdbookUser>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setBookId(updateValidate.getBookId());
        model.setMarkUserId(updateValidate.getMarkUserId());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        wisdbookUserMapper.updateById(model);
    }

    /**
     * 标记任务删除
     *
     * @author SwAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        WisdbookUser model = wisdbookUserMapper.selectOne(
                new QueryWrapper<WisdbookUser>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        wisdbookUserMapper.updateById(model);
    }

}
